#include "inheritable_handle.hpp"
#include "exception.hpp"

namespace judge {

inheritable_handle::inheritable_handle(HANDLE handle)
	: handle_(_create_handle(handle))
{}

inheritable_handle::~inheritable_handle()
{
	HANDLE h = handle();
	if (h != NULL)
		::CloseHandle(h);
}

HANDLE inheritable_handle::_create_handle(HANDLE handle)
{
	if (handle == NULL)
		return NULL;

	HANDLE result;
	BOOL success = ::DuplicateHandle(GetCurrentProcess(), handle,
		GetCurrentProcess(), &result, 0, TRUE, DUPLICATE_SAME_ACCESS);
	if (!success) {
		throw win32_exception(::GetLastError());
	}
	return result;
}

HANDLE inheritable_handle::handle()
{
	return handle_;
}

}
